#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime

from bottle import Bottle
from bottle import debug, run
from bottle import jinja2_view as view
from bottle import redirect, abort, static_file
from bottle import jinja2_template as template
from bottle import request, response, local

from models import Entry
from autumn.db.query import Query

app = Bottle()

@app.route('/list/recent')
def handle_list_recent():
    objlist = Entry.get().order_by('create_time', 'DESC')[:]

    items = [dict(id=it.id,remark=it.remark,create_time=it.create_time,up_num=it.up_num) \
             for it in objlist]
    return dict(
        ret=0,
        items=items
        )

@app.route('/list/day_top')
def handle_list_day_top():
    now = datetime.datetime.now()
    t = datetime.timedelta(days=1)
    point_day = now - t

    sql = 'select * from entry where create_time>=? order by up_num desc'
    objlist = Query.sql(sql, [point_day])
    return dict(
        ret=0,
        items=objlist
        )

@app.route('/list/week_top')
def handle_list_week_top():
    now = datetime.datetime.now()
    t = datetime.timedelta(days=7)
    point_day = now - t

    sql = 'select * from entry where create_time>=? order by up_num desc'
    objlist = Query.sql(sql, [point_day])
    return dict(
        ret=0,
        items=objlist
        )

@app.post('/up/<entry_id:int>')
def handle_up(entry_id):
    objlist = Entry.get(id=entry_id)
    if not objlist:
        return dict(
            ret = 1,
            msg = u"数据不存在"
            )

    obj = objlist[0]

    obj.up_num += 1
    obj.save()

    return dict(
        ret = 0
        )

@app.post('/del/<entry_id:int>')
def handle_del(entry_id):
    objlist = Entry.get(id=entry_id)
    if not objlist:
        return dict(
            ret = 1,
            msg = u"数据不存在"
            )

    obj = objlist[0]

    obj.delete()

    return dict(
        ret = 0
        )
